package com.example.vuebackend.controller;

import com.example.vuebackend.dto.Person;
import com.example.vuebackend.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @GetMapping("/{page}/{size}")
    public Page<Person> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        PageRequest request = PageRequest.of(page, size);
        return personService.findAll(request);
    }

    @GetMapping("/{id}")
    public Person findById(@PathVariable("id") Integer id) {
        return personService.findById(id);
    }

    @PostMapping
    public String save(@RequestBody Person person) {
        Person result = personService.save(person);
        if (result != null) {
            return "success";
        } else {
            return "error";
        }
    }

    @PutMapping
    public String update(@RequestBody Person person) {
        Person result = personService.save(person);
        if (result != null) {
            return "success";
        } else {
            return "error";
        }
    }

    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable("id") Integer id) {
        personService.deleteById(id);
    }
}
